package utils

import (
	"encoding/json"
	"math/rand"
	"reflect"
	"time"
	"unsafe"
)

func JsonToString(status int, count int, data interface{}) string { //test-time 0ns
	m := make(map[string]interface{})
	m["status"] = status
	m["count"] = count
	m["data"] = data
	if str, err := json.Marshal(m); err != nil {
		return JsonToString(0, 0, "")
	} else {
		return BytesToString(str)
	}
}

func JsonToBytes(status int, count int, data interface{}) []byte { //test-time 0ns
	m := make(map[string]interface{})
	m["status"] = status
	m["count"] = count
	m["data"] = data
	if str, err := json.Marshal(m); err != nil {
		return JsonToBytes(0, 0, "")
	} else {
		return str
	}
}

func GetRandomString(lens int64) string { //test-time 0ns
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	var i int64
	for i = 0; i < lens; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func BytesToString(b []byte) (s string) {
	pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
	pstring.Data = pbytes.Data
	pstring.Len = pbytes.Len
	return
}

func StringToBytes(s string) (b []byte) {
	pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
	pbytes.Data = pstring.Data
	pbytes.Len = pstring.Len
	pbytes.Cap = pstring.Len
	return
}
